package com.joker.aigc.tools.service.impl;

import cn.hutool.core.io.FileUtil;
import com.joker.aigc.tools.domian.dto.NormalSqlStructureDTO;
import com.joker.aigc.tools.domian.po.TableParsePO;
import com.joker.aigc.tools.service.SqlConvertService;
import com.joker.aigc.utils.AssertUtil;
import com.joker.aigc.tools.utils.SqlToMarkdownUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Desciption:
 * @Author: feixiang.li
 * @date: 2024-08-05 12:40
 **/
@Slf4j
@Service
public class SqlConvertServiceImpl implements SqlConvertService {


    /**
     * 开始转换
     *
     * @param sql 创建表语句
     * @return
     */
    @Override
    public String convertSqlToMarkdown(String sql) {
        NormalSqlStructureDTO normalSqlStructureDTO = SqlToMarkdownUtils.convertSqlToMarkdown(sql);
        AssertUtil.isNotEmpty(normalSqlStructureDTO, "对不起SQL不能为空");
        return SqlToMarkdownUtils.writeMarkdown(normalSqlStructureDTO);
    }

    @Override
    public String convertDtoToMarkdown(String dto) {
        return SqlToMarkdownUtils.convertDtoToMarkdown(dto);
    }

    @Override
    public String getCreateTableSql(String sql1, String sql2) {
        TableParsePO tableParsePO = new TableParsePO();
        return tableParsePO.addSql(sql1, sql2);
    }

    /**
     * 获取创建表语句
     *
     * @param sql1 文件1
     * @param sql2 文件2
     * @return 创建表语句
     */
    @Override
    public String getCreateTableSql(MultipartFile sql1, MultipartFile sql2) {
        try {
            File file = new File(sql1.getOriginalFilename());
            sql1.transferTo(file);
            String s1 = FileUtil.readString(file, StandardCharsets.UTF_8);
            File file2 = new File(sql2.getOriginalFilename());
            sql2.transferTo(file2);
            String s2 = FileUtil.readString(file2, StandardCharsets.UTF_8);
            TableParsePO tableParsePO = new TableParsePO();
            return tableParsePO.addSql(s1, s2);
        } catch (IOException e) {
            log.error("解析失败: ", e);
        }
        return "";
    }
}
